<template>
    <div style="display: inline-block;">
        <el-select v-model="ids" multiple clearable filterable remote reserve-keyword :placeholder="props.placeholder" :remote-method="remoteMethod" :loading="loading" :disabled="props.disabled" style="width: 100%" @change="change1">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>        
    </div>
</template>
  
<script setup lang="ts">
import userApi from '@/api/system/user';
import roleApi from '@/api/system/role';

const props = defineProps({
    property: String,    
    placeholder:String,
    defaultList: {
        type: Array as () => ListItem[],
        default: () => [] // 确保默认值是一个空数组
    },
    disabled: {
        type: Boolean,
        default: false
    },
})

let $emit = defineEmits(['save']);

interface ListItem {
    id: number;
    name: string
}
watch(() => props.defaultList, (newVal: ListItem[]) => {
    console.log('执行监听props.defaultList')
    setDefault(newVal);
})
const setDefault = async (newVal: ListItem[]) => {
    if (Array.isArray(newVal)) {
        ids.value = newVal.map(item => item.id);
        options.value = [...newVal];
        items.value = [...newVal];
        await nextTick();
    }
}
const options = ref<ListItem[]>([])
const ids = ref<number[]>([])
const loading = ref(false)
const items = ref<ListItem[]>([])

onMounted(() => {
    init()
})
const init = async() => {
    if(props.defaultList&&props.defaultList.length>0){
        // 如果存在默认值，直接赋值
        await setDefault(props.defaultList);
    }else{
        remoteMethod('');
    }
}
const remoteMethod = async (query: string) => {
    options.value = []
    if(props.property == 'forUserId'){ // 用户
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await userApi.userSelect(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }else if(props.property == 'forRoleId'){ //角色
        try {
            loading.value = true;
            let searchKey = query?query:'';
            let results = await roleApi.roleSelect(searchKey) as any;
            if (results) {
                options.value = results;
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }
}
const change1 = (val: any) => {
    if(items.value.length > val.length){
        items.value = items.value.filter(item => val.includes(item.id));
    }else if(items.value.length < val.length){
        // 从 items 数组中提取所有的 id
        const itemIds = items.value.map(item => item.id);
        // 找到 val 中的值，这些值不在 ids 数组中
        const unmatchedValues = val.filter((valItem:number) => !itemIds.includes(valItem));
        const newItems = unmatchedValues.map( (id:number) => options.value.find(item => item.id === id));
        items.value = [...items.value, ...newItems];
    }
    $emit('save', {
        ids:val,
        items:items.value
    });
}
</script>
  
<style scoped lang="scss">
</style>
